// 内容脚本
class ContentScript {
    constructor() {
        this.init();
    }

    init() {
        this.bindEvents();
        this.createResultModal();
    }

    // 绑定事件
    bindEvents() {
        // 监听来自后台脚本的消息
        chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
            this.handleMessage(request, sender, sendResponse);
            return true;
        });

        // 监听键盘快捷键
        document.addEventListener('keydown', (e) => {
            this.handleKeydown(e);
        });
    }

    // 处理消息
    handleMessage(request, sender, sendResponse) {
        switch (request.action) {
            case 'showResult':
                this.showResult(request.title, request.result);
                sendResponse({ success: true });
                break;
            case 'getSelectedText':
                const selectedText = window.getSelection().toString();
                sendResponse({ text: selectedText });
                break;
            default:
                sendResponse({ success: false, error: 'Unknown action' });
        }
    }

    // 处理键盘快捷键
    handleKeydown(e) {
        // Ctrl+Shift+D 打开开发工具箱
        if (e.ctrlKey && e.shiftKey && e.key === 'D') {
            e.preventDefault();
            this.openDevToolbox();
        }

        // Ctrl+Shift+J 格式化选中的JSON
        if (e.ctrlKey && e.shiftKey && e.key === 'J') {
            e.preventDefault();
            this.formatSelectedJSON();
        }

        // Ctrl+Shift+X 格式化选中的XML
        if (e.ctrlKey && e.shiftKey && e.key === 'X') {
            e.preventDefault();
            this.formatSelectedXML();
        }
    }

    // 打开开发工具箱
    openDevToolbox() {
        chrome.runtime.sendMessage({ action: 'openPopup' });
    }

    // 格式化选中的JSON
    async formatSelectedJSON() {
        const selectedText = window.getSelection().toString().trim();
        if (!selectedText) {
            this.showToast('请先选择JSON文本', 'warning');
            return;
        }

        try {
            const parsed = JSON.parse(selectedText);
            const formatted = JSON.stringify(parsed, null, 2);
            await this.copyToClipboard(formatted);
            this.showToast('JSON格式化结果已复制到剪贴板', 'success');
            this.showResult('JSON格式化结果', formatted);
        } catch (error) {
            this.showToast(`JSON格式错误: ${error.message}`, 'error');
        }
    }

    // 格式化选中的XML
    async formatSelectedXML() {
        const selectedText = window.getSelection().toString().trim();
        if (!selectedText) {
            this.showToast('请先选择XML文本', 'warning');
            return;
        }

        try {
            const formatted = this.formatXML(selectedText);
            await this.copyToClipboard(formatted);
            this.showToast('XML格式化结果已复制到剪贴板', 'success');
            this.showResult('XML格式化结果', formatted);
        } catch (error) {
            this.showToast(`XML格式错误: ${error.message}`, 'error');
        }
    }

    // XML格式化
    formatXML(xml) {
        const PADDING = ' '.repeat(2);
        const reg = /(>)(<)(\/*)/g;
        let pad = 0;

        xml = xml.replace(reg, '$1\r\n$2$3');

        return xml.split('\r\n').map((node) => {
            let indent = 0;
            if (node.match(/.+<\/\w[^>]*>$/)) {
                indent = 0;
            } else if (node.match(/^<\/\w/) && pad > 0) {
                pad -= 1;
            } else if (node.match(/^<\w[^>]*[^/]>.*$/)) {
                indent = 1;
            } else {
                indent = 0;
            }

            const padding = PADDING.repeat(pad);
            pad += indent;

            return padding + node;
        }).join('\r\n');
    }

    // 创建结果模态框
    createResultModal() {
        if (document.getElementById('devToolboxModal')) {
            return;
        }

        const modal = document.createElement('div');
        modal.id = 'devToolboxModal';
        modal.innerHTML = `
            <div class="devtoolbox-modal-overlay">
                <div class="devtoolbox-modal-content">
                    <div class="devtoolbox-modal-header">
                        <h3 id="devToolboxModalTitle">处理结果</h3>
                        <button class="devtoolbox-modal-close">&times;</button>
                    </div>
                    <div class="devtoolbox-modal-body">
                        <textarea id="devToolboxModalResult" readonly></textarea>
                    </div>
                    <div class="devtoolbox-modal-footer">
                        <button id="devToolboxCopyResult" class="devtoolbox-btn devtoolbox-btn-primary">复制</button>
                        <button class="devtoolbox-modal-close devtoolbox-btn devtoolbox-btn-secondary">关闭</button>
                    </div>
                </div>
            </div>
        `;

        // 添加样式
        const style = document.createElement('style');
        style.textContent = `
            #devToolboxModal {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                z-index: 999999;
                display: none;
            }
            
            .devtoolbox-modal-overlay {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                display: flex;
                justify-content: center;
                align-items: center;
            }
            
            .devtoolbox-modal-content {
                background: white;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
                width: 90%;
                max-width: 600px;
                max-height: 80%;
                display: flex;
                flex-direction: column;
            }
            
            .devtoolbox-modal-header {
                padding: 20px;
                border-bottom: 1px solid #e9ecef;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            
            .devtoolbox-modal-header h3 {
                margin: 0;
                color: #333;
                font-size: 18px;
                font-weight: 600;
            }
            
            .devtoolbox-modal-close {
                background: none;
                border: none;
                font-size: 24px;
                cursor: pointer;
                color: #999;
                padding: 0;
                width: 30px;
                height: 30px;
                display: flex;
                justify-content: center;
                align-items: center;
            }
            
            .devtoolbox-modal-close:hover {
                color: #333;
            }
            
            .devtoolbox-modal-body {
                padding: 20px;
                flex: 1;
                overflow: hidden;
            }
            
            #devToolboxModalResult {
                width: 100%;
                height: 300px;
                border: 2px solid #e9ecef;
                border-radius: 6px;
                padding: 12px;
                font-family: 'Courier New', monospace;
                font-size: 14px;
                resize: none;
                outline: none;
                background: #f8f9fa;
            }
            
            .devtoolbox-modal-footer {
                padding: 20px;
                border-top: 1px solid #e9ecef;
                display: flex;
                justify-content: flex-end;
                gap: 10px;
            }
            
            .devtoolbox-btn {
                padding: 8px 16px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
                font-weight: 500;
                transition: all 0.3s ease;
            }
            
            .devtoolbox-btn-primary {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
            }
            
            .devtoolbox-btn-primary:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
            }
            
            .devtoolbox-btn-secondary {
                background: #6c757d;
                color: white;
            }
            
            .devtoolbox-btn-secondary:hover {
                background: #5a6268;
            }
        `;

        document.head.appendChild(style);
        document.body.appendChild(modal);

        // 绑定事件
        modal.querySelectorAll('.devtoolbox-modal-close').forEach(btn => {
            btn.addEventListener('click', () => this.hideResult());
        });

        modal.querySelector('#devToolboxCopyResult').addEventListener('click', () => {
            this.copyModalResult();
        });

        // 点击遮罩层关闭
        modal.querySelector('.devtoolbox-modal-overlay').addEventListener('click', (e) => {
            if (e.target === e.currentTarget) {
                this.hideResult();
            }
        });

        // ESC键关闭
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && modal.style.display === 'block') {
                this.hideResult();
            }
        });
    }

    // 显示结果
    showResult(title, result) {
        const modal = document.getElementById('devToolboxModal');
        const titleElement = document.getElementById('devToolboxModalTitle');
        const resultElement = document.getElementById('devToolboxModalResult');

        if (modal && titleElement && resultElement) {
            titleElement.textContent = title;
            resultElement.value = result;
            modal.style.display = 'block';
        }
    }

    // 隐藏结果
    hideResult() {
        const modal = document.getElementById('devToolboxModal');
        if (modal) {
            modal.style.display = 'none';
        }
    }

    // 复制模态框结果
    async copyModalResult() {
        const resultElement = document.getElementById('devToolboxModalResult');
        if (resultElement) {
            await this.copyToClipboard(resultElement.value);
            this.showToast('已复制到剪贴板', 'success');
        }
    }

    // 复制到剪贴板
    async copyToClipboard(text) {
        try {
            await navigator.clipboard.writeText(text);
        } catch (error) {
            // 降级方案
            const textarea = document.createElement('textarea');
            textarea.value = text;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);
        }
    }

    // 显示提示消息
    showToast(message, type = 'info') {
        // 移除现有提示
        const existingToast = document.getElementById('devToolboxToast');
        if (existingToast) {
            existingToast.remove();
        }

        // 创建新提示
        const toast = document.createElement('div');
        toast.id = 'devToolboxToast';
        toast.textContent = message;
        
        // 样式
        const baseStyle = {
            position: 'fixed',
            top: '20px',
            right: '20px',
            padding: '12px 20px',
            borderRadius: '6px',
            color: 'white',
            fontSize: '14px',
            fontWeight: '500',
            zIndex: '999999',
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.2)',
            transition: 'all 0.3s ease',
            transform: 'translateX(100%)',
            opacity: '0'
        };

        // 根据类型设置颜色
        const typeColors = {
            success: '#28a745',
            error: '#dc3545',
            warning: '#ffc107',
            info: '#17a2b8'
        };

        Object.assign(toast.style, baseStyle);
        toast.style.background = typeColors[type] || typeColors.info;

        document.body.appendChild(toast);

        // 动画显示
        setTimeout(() => {
            toast.style.transform = 'translateX(0)';
            toast.style.opacity = '1';
        }, 10);

        // 3秒后自动隐藏
        setTimeout(() => {
            toast.style.transform = 'translateX(100%)';
            toast.style.opacity = '0';
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.remove();
                }
            }, 300);
        }, 3000);
    }
}

// 初始化内容脚本
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        new ContentScript();
    });
} else {
    new ContentScript();
}